package at.fhj.itm10.ticketmaster.services.impl;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import at.fhj.itm10.ticketmaster.services.ServiceException;

/**
 * Abstract service.
 * Provides connection and basic sql orders(commit, begin, rollback).
 * @author Egon Teiniker
 * @author Wolfgang Gaar
 */
/* package private */ abstract class AbstractService {
	private final Logger logger = Logger.getLogger(AbstractService.class);

	protected Connection connection;

	protected Connection getConnection() {
		return connection;
	}

	public void setConnection(Connection connection) {
		if (connection == null)
			throw new NullPointerException("connection");
		this.connection = connection;
	}

	protected void closeConnection() {
		try {
			if (connection != null)
				connection.close();
		} catch (SQLException e) {
			logger.error("JDBC connection close failure", e);
		}
	}

	protected void begin() throws ServiceException {
		try {
			connection.setAutoCommit(false);
		} catch (SQLException e) {
			throw new ServiceException("transaction begin failure", e);
		}
	}

	protected void commit() throws ServiceException {
		try {
			connection.commit();
			connection.setAutoCommit(true);
		} catch (SQLException e) {
			throw new ServiceException("transaction commit failure", e);
		}
	}

	protected void rollback() throws ServiceException {
		try {
			connection.rollback();
		} catch (SQLException e) {
			throw new ServiceException("transaction rollback failure", e);
		}
	}
}